/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ControlLayer;
import ModelLayer.*;
import DBLayer.*;

/**
 *
 * @author Martin
 */
public class CtrlSalesOrder {
   
    
    private CtrlCustomer ctrlCustomer;
    private CtrlProduct ctrlProduct;
    private CtrlInvoice ctrlInvoice;
    private IFDBSalesOrder dbSalesOrder = new DBSalesOrder();
    private IFDBSalesLineItem dbSalesLineItem = new DBSalesLineItem();
    
    /**
     * Creates a new instance of CtrlCustomer
     */
    public CtrlSalesOrder()
    {
        ctrlCustomer = new CtrlCustomer();
        ctrlProduct = new CtrlProduct();
        ctrlInvoice = new CtrlInvoice();
    }
//-----------------------------------------------------------------------------    
    
    public SalesOrder findSalesOrder(int orderId)
    {
        IFDBSalesOrder dbSale = new DBSalesOrder();
        return dbSale.findSalesOrder(orderId, false);
    }
//-----------------------------------------------------------------------------
    public void insertSalesOrder(SalesOrder sale)
      {
           IFDBSalesOrder dbSale = new DBSalesOrder();
           dbSale.insertSalesOrder(sale);
      }
    
    public SalesOrder startSale(String date, String deliveryDate, int customerId)
    {
        Customer c = ctrlCustomer.findPerson(customerId);
        
        SalesOrder salesOrder = new SalesOrder();
        salesOrder.setDate(date);
        salesOrder.setDeliveryDate(deliveryDate);
        salesOrder.setCustomer(c);
        salesOrder.setDeliveryStatus("false");
        salesOrder.setInvoice(null);
        salesOrder.setTotal(0);
        
        dbSalesOrder.insertSalesOrder(salesOrder);
        
        return dbSalesOrder.findSalesOrder(dbSalesOrder.getMaxId(), false);
    }
    
    public void enterItem(int productId, int amount, SalesOrder salesOrder)
    {
        System.out.println("Product id start " + productId);
        Product p = new Product();
        p = ctrlProduct.findProduct(productId);
        System.out.println("Product Id " + p.getProductId());
        //SalesOrder sale = dbSalesOrder.findSalesOrder(orderId, false);
        
        SalesLineItem sli = new SalesLineItem();
        sli.setProduct(p);
        sli.setAmount(amount);
        sli.setSalesOrder(salesOrder);
        
        dbSalesLineItem.insertSalesLineItem(sli);
    }
    
    public void endSale(SalesOrder salesOrder)
    {
        dbSalesOrder.calcTotalAmounts(salesOrder);
        Invoice invoice = new Invoice();
        invoice.setDate(salesOrder.getDate());
        invoice.setAmount(salesOrder.getTotal());
        invoice.setPaymentDate("0100-01-01");
        ctrlInvoice.insertInvoice(invoice);
        
        //salesOrder.setInvoice(ctrlInvoice.findInvoice(ctrlInvoice.getMaxId()));
        //dbSalesOrder.updateSalesOrder(salesOrder);
        // skal lave update invoiceNo i SalesOrder
    }
}
